package com.etoak.controller;

import com.etoak.entity.User;
import com.etoak.service.UserService;

import com.etoak.util.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 用户查询接口
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public User getUser(@PathVariable int id) {
        return userService.getById(id);
    }

    @PostMapping
    public Object addUser(@RequestBody User user) {
        log.info("id is {}", user);
        Map<String,Object> result = new HashMap<>();

        try {
            ValidatorUtil.validate(user);

        }catch (Exception e) {
            log.error(e.getMessage(), e);

            result.put("code", 201);
            result.put("msg", e.getMessage());
            return result;

        }
        userService.addUser(user);
        result.put("code",200);
        result.put("msg","success");
        return result;

    }
    
    @PutMapping("/{id}")
    public Object updateUser(@PathVariable int id, @RequestBody User user) {
        User userId = getUser(id);
        if(userId == null){
            return "没有该用户信息 请重新输入";
        }
        log.info("user is {}", user);
        user.setId(id);
        userService.updateUser(user);
        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","success");
        return result;

    }

    @DeleteMapping("/{id}")
    public Object deleteUser(@PathVariable int id) {
        log.info("id is {}" ,id);
        User userId = getUser(id);

        if(userId == null){
            return "没有该用户信息 请重新输入";
        }
        userService.deleteUser(id);

        Map<String,Object> result = new HashMap<>();
        result.put("code",200);
        result.put("msg","success");
        return result;

    }
}















